package com.simplesoftwares.client.library.appstructure.tablescreen;

import java.util.ArrayList;

import com.google.code.p.gwtchismes.client.GWTCAlert;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.simplesoftwares.client.library.ReturnFromServer;
import com.simplesoftwares.client.library.appstructure.EntityPresenter;
import com.simplesoftwares.client.library.appstructure.SearchPopUpScreen;
import com.simplesoftwares.client.library.appstructure.SuperModel;
import com.simplesoftwares.client.library.appstructure.UiScreen;
import com.simplesoftwares.client.library.appstructure.formscreen.FormScreen;

/**
 * Presenter for Table Screens.
 * @author Kamala
 *
 * @param <T>
 */
public abstract class TableScreenPresenter<T extends SuperModel> extends EntityPresenter<T> {
	
	/**
     * Reffers to {@link TableScreen} type screen
     */
   protected  TableScreen<T> tableScreen;
    
    /**
	 * Instantiates a new TableScreenPresenter with passed view & model
	 * @param view Screen for this presenter
	 * @param model Model for this presenter
	 */
	public TableScreenPresenter(TableScreen<T> view, T model) {
		super(view, model);
		tableScreen=view;
	}

	/**
	 * Saves the whole table 
	 * To Do: Inefecient as we need to save only changed entites. Chalange for komal
	 */
	@Override
	protected void reactOnSave() {
	     view.showWaitSymbol();
	     final ArrayList<SuperModel>list=new ArrayList<SuperModel>();
	     list.addAll(this.tableScreen.superTable.getDataprovider().getList());
	     service.save(list, new AsyncCallback<ArrayList<ReturnFromServer>>() 
	    		 {

				@Override
				public void onFailure(Throwable caught) {
					view.showDialogMessage("Data Save Unsuccessful! Try again.");
					view.hideWaitSymbol();
				}

				@Override
				public void onSuccess(ArrayList<ReturnFromServer> result) {
					view.hideWaitSymbol();
					for(int i=0;i<result.size();i++)
					{
						list.get(i).setId(result.get(i).id);
						list.get(i).setCount(result.get(i).count);
					}
					view.showDialogMessage("Data Successfully Saved !",GWTCAlert.OPTION_ROUNDED_BLUE ,GWTCAlert.OPTION_ANIMATION);
					view.setToViewState();
					
					
				}
			});
	     
	     
	     
		
	}

	

	@Override
	public void reactToProcessBarEvents(ClickEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	protected void makeNewModel() {
		// TODO Auto-generated method stub
		
	}

	@Override
	protected void reactOnGo() {
		// TODO Auto-generated method stub
		super.reactOnGo();
		SearchPopUpScreen<T>popup=view.getSearchpopupscreen();
		if(popup!=null)
			popup.hidePopUp();
	}

	@Override
	public void reactOnDownload() {
		// TODO Auto-generated method stub
		
	}

	

	

	
}
